<template>
  <el-dialog
    v-model="visibleLocal"
    title="历史报表"
    width="1500px"
    @close="onClose"
    :close-on-click-modal="false"
  >
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <!-- <el-form-item label="设备ID" prop="deviceId">
          <el-input
            v-model="queryParams.deviceId"
            placeholder="请输入设备ID"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
            :disabled="true"
          />
        </el-form-item> -->
        <el-form-item label="名称" prop="reportName">
          <el-input
            v-model="queryParams.reportName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select
            v-model="queryParams.dataType"
            placeholder="请选择数据类型"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_REPORT_DATA_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="数量" prop="mqttNum">
          <el-input
            v-model="queryParams.mqttNum"
            placeholder="请输入数量"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item> -->
        <el-form-item label="报表类型" prop="reportType">
          <el-select
            v-model="queryParams.reportType"
            placeholder="请选择报表类型"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_REPORT_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="handleCreate"
            v-hasPermi="['mqtt:device-report:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['mqtt:device-report:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="报表ID" align="center" prop="id" />
        <!-- <el-table-column label="设备ID" align="center" prop="deviceId" /> -->
        <el-table-column label="名称" align="center" prop="reportName" />
        <el-table-column label="数据类型" align="center" prop="dataType">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MQTT_DEVICE_REPORT_DATA_TYPE" :value="scope.row.dataType" />
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="mqttNum" />
        <el-table-column label="报表类型" align="center" prop="reportType">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.MQTT_DEVICE_REPORT_TYPE" :value="scope.row.reportType" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id, list, props.row.id)"
              v-hasPermi="['mqtt:device-report:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['mqtt:device-report:delete']"
            >
              删除
            </el-button>
            <el-button link type="warning" @click="openSubscribeWaterDialog(scope.row)">
              数据管理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <DeviceReportForm ref="formRef" @success="getList" />
    <SubscribeWaterDialog
      v-model:visible="subscribeWaterDialogVisible"
      :device-row="subscribeWaterDeviceRow"
      :report-row="subscribeWaterReportRow"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceReportApi, DeviceReportVO } from '@/api/mqtt/devicereport'
import DeviceReportForm from './DeviceReportForm.vue'
import SubscribeWaterDialog from '../subscribewater/index.vue'
import { ref, reactive, watch } from 'vue'

const props = defineProps<{ visible: boolean; row: any }>()
const emit = defineEmits(['update:visible'])

const visibleLocal = ref(props.visible)
watch(
  () => props.visible,
  (v) => (visibleLocal.value = v)
)
const onClose = () => {
  visibleLocal.value = false
  emit('update:visible', false)
}

/** MQTT报表分类 列表 */
defineOptions({ name: 'DeviceReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DeviceReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: undefined,
  mqttConfigId: undefined,
  reportName: undefined,
  dataType: undefined,
  mqttNum: undefined,
  reportType: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 监听 row 变化，自动刷新 deviceId
watch(
  () => props.row,
  (row) => {
    if (row && row.id) {
      queryParams.deviceId = row.id
      getList()
    }
  },
  { immediate: true }
)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log('传递过来的参数', props.row)
    queryParams.mqttConfigId = props.row?.mqttConfigId
    const data = await DeviceReportApi.getDeviceReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (
  type: string,
  id?: number,
  existingList?: DeviceReportVO[],
  deviceId?: number
) => {
  formRef.value.open(type, id, existingList, deviceId)
}

const handleCreate = () => {
  console.log('=== handleCreate 开始 ===')
  console.log('list.value:', list.value)
  console.log('list.value 长度:', list.value.length)
  console.log('props.row.id:', props.row.id)

  // 传递当前列表数据，用于校验数据类型是否重复
  openForm('create', undefined, list.value, props.row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceReportApi.deleteDeviceReport(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceReportApi.exportDeviceReport(queryParams)
    download.excel(data, 'MQTT报表分类.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const subscribeWaterDialogVisible = ref(false)
const subscribeWaterDeviceRow = ref()
const subscribeWaterReportRow = ref()
const openSubscribeWaterDialog = (reportRow: any) => {
  subscribeWaterDeviceRow.value = props.row
  subscribeWaterReportRow.value = reportRow
  subscribeWaterDialogVisible.value = true
}
</script>
